package com.didispace;

import wn.tcpip.socket.util.Byte2Hex;
import wn.tcpip.socket.util.ProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.TimeUnit;

public class GpsClientHandler extends SimpleChannelInboundHandler<String>{

	public final static String LOGIN = "78780D010868120129036080004769970D0A";//登录包
	public final static String STATUS = "78780813460604098C8B820D0A";//状态包
	public final static String GPSINFO = "78781F12%sC602409FDB099D2D68191C76014E0379180075AA0098EF2A0D0A";//GPS信息包
	public final static String GPSSTATUS = "78782316%sC60C47A9480271BABF0028088A01D21E00FA0000000203040005CBE90D0A";//GPS信息包
	public static volatile boolean success = false;
	public static volatile boolean shutdown = false;
	//public final static String LOGIN = "78780D010353419032332707004B7DB80D0A";//
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		byte[] req = Byte2Hex.HexString2Bytes(LOGIN);
		ByteBuf msg2 = Unpooled.buffer(req.length);
		msg2.writeBytes(req);
		System.out.println("设备注册");
		ctx.writeAndFlush(msg2);
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					if (success && !shutdown) {
						byte[] req = Byte2Hex.HexString2Bytes(String.format(GPSSTATUS, ProtocolUtil.buildHexDateTime()));
						ByteBuf msg = Unpooled.buffer(req.length);
						msg.writeBytes(req);
						ctx.writeAndFlush(msg);
					}
					try {
						TimeUnit.SECONDS.sleep(1);//每10秒发送一次GPS信息
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

		ctx.writeAndFlush(msg);
	}

}
